import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Input,
  Radio,
  Form,
  Card,
  Table,
  Checkbox,
  Modal,
  Upload,
  Space,
  Switch,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { connect } from "umi";
import { getItem } from "@/utils/localstorage";
import { TOKEN } from "@/constants";
import { namespace } from "./configFile";
import { useEffect, useState, useRef } from "react";
import styles from "./styles.less";

const Page = (props) => {
  const { dispatch, submitLoading } = props;
  const [open, setOpen] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [checked, setChecked] = useState(false);
  const [fileList, setFileList] = useState([]);

  const actionRef = useRef();

  const [form] = Form.useForm();
  const [form2] = Form.useForm();

  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
      callback: (res) => {
        // console.log(res)
        let data = {};
        setChecked(res[0].openFlag === "0" ? true : false);
        res.forEach((element, index) => {
          data[index] = element;
          if (index == 6) {
            data[index].value = element.value
              ? [
                  {
                    uid: "1",
                    name: element.value,
                    status: "done",
                    url: element.value,
                  },
                ]
              : [];
          }
        });
        setDataSource(res.slice(2, 5));
        form.setFieldsValue(data);
      },
    });
  }, []);

  const editInfo = (params) => {
    let { id, name, value } = params;
    if (value && value !== "") {
      value = JSON.parse(value);
    }
    form2.setFieldsValue({ id, name, value });
    setOpen(true);
  };
  const submitForm = async () => {
    const res = await form.validateFields();
    if (res) {
      dispatch({
        type: `${namespace}/submitItem`,
        params: [
          {
            id: res[0].id,
            openFlag: res[0].openFlag,
            value: res[0].value,
          },
          {
            id: res[1].id,
            openFlag: res[1].openFlag,
            value: res[1].value,
          },
          ...dataSource.map((d) => {
            let { id, value, openFlag } = d;
            return {
              id,
              value,
              openFlag,
            };
          }),
          {
            id: res[5].id,
            openFlag: res[5].openFlag,
            value: res[6].value
              ? Array.isArray(res[6].value)
                ? res[6].value[0].url
                : res[6].value
              : "",
          },
          {
            id: res[6].id,
            openFlag: res[6].openFlag,
            value: res[6].value
              ? Array.isArray(res[6].value)
                ? res[6].value[0].url
                : res[6].value
              : "",
          },
        ],
      });
    }
    console.log(res);
  };
  const normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const handleChange = (e) => {
    let newFileList = [...e.fileList];
    if (e.file.status === "uploading") {
      return;
    }

    if (e.file.status === "done") {
      newFileList = newFileList.map((file) => {
        if (file.response) {
          file.url = file.response.data;
        }
        return file;
      });
      setFileList(newFileList);
    }
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  return (
    <PageContainer>
      <Card>
        <Form
          form={form}
          // layout='inline'
          // labelCol={{span: 5}}
          // wrapperCol={{span: 19}}
        >
          <Form.Item name={[0, "id"]} hidden>
            <Input />
          </Form.Item>

          <Form.Item label="教室冲突验证" name={[0, "openFlag"]} hidden>
            <Switch
              checked={checked}
              onClick={(value) => {
                console.log(value);
                setChecked(value);
                form.setFieldValue([0, "openFlag"], value ? "0" : "1");
              }}
            />
          </Form.Item>

          <Form.Item name={[1, "id"]} hidden>
            <Input />
          </Form.Item>
          <Form.Item label="授课员工称谓" name={[1, "value"]} hidden>
            <Radio.Group>
              <Radio value={"教练"}>教练</Radio>
              <Radio value={"老师"}>老师</Radio>
              <Radio value={"导师"}>导师</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="上课说明设置" hidden>
            <ProTable
              search={false}
              actionRef={actionRef}
              pagination={false}
              scroll={{ x: 1000 }}
              columns={[
                { title: "内容项", dataIndex: "name" },
                {
                  title: "详细说明",
                  dataIndex: "value",
                  render: (_, record) => {
                    let value =
                      record.value && record.value !== ""
                        ? JSON.parse(record.value)
                        : {};
                    return value.content || "";
                  },
                },
                {
                  title: "排序值",
                  dataIndex: "value",
                  render: (_, record) => {
                    let value =
                      record.value && record.value !== ""
                        ? JSON.parse(record.value)
                        : {};
                    return value.sort || "";
                  },
                },
                {
                  title: "状态",
                  dataIndex: "openFlag",
                  render: (_) => (_ === "0" ? "开启" : "禁用"),
                },
                {
                  title: "操作",
                  fixed: "right",
                  dataIndex: "options",
                  align: "center",
                  render: (_, record) => (
                    <div>
                      <Button type="link" onClick={() => editInfo(record)}>
                        编辑
                      </Button>
                      {record.openFlag === "0" ? (
                        <Button
                          type="link"
                          onClick={() => {
                            record.openFlag = "1";
                            setDataSource(dataSource);
                            actionRef.current?.reload();
                          }}
                        >
                          禁用
                        </Button>
                      ) : (
                        <Button
                          type="link"
                          onClick={() => {
                            record.openFlag = "0";
                            setDataSource(dataSource);
                            actionRef.current?.reload();
                          }}
                        >
                          启用
                        </Button>
                      )}
                    </div>
                  ),
                },
              ]}
              dataSource={dataSource}
            />
          </Form.Item>
          <Form.Item name={[5, "id"]} hidden>
            <Input />
          </Form.Item>
          <Form.Item label="品牌粉丝群二维码" name={[5, "value"]} hidden>
            <Input
              style={{ maxWidth: 300 }}
              maxLength={20}
              placeholder="请输入"
            />
          </Form.Item>
          <Form.Item name={[6, "id"]} hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="品牌粉丝群二维码"
            name={[6, "value"]}
            getValueFromEvent={normFile}
            extra="图片支持jpg/png格式"
            valuePropName="fileList"
          >
            <Upload
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              fileList={fileList}
              maxCount={1}
              accept=".png,.jpg,.jpeg"
              headers={{
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
                Authorization: getItem(TOKEN),
              }}
              onChange={handleChange}
              action="/spark-frontend/system/user/uploadPic"
              onPreview={(e) => {
                window.open(e.url || e.response.url);
              }}
            >
              {fileList.length >= 9 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Button onClick={submitForm} loading={submitLoading} type="primary">
            确定
          </Button>
        </Form>
      </Card>

      <Modal
        forceRender
        title="上课说明编辑"
        open={open}
        onCancel={() => setOpen(!open)}
        footer={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button
              onClick={async () => {
                let res = await form2.validateFields();
                if (res) {
                  console.log(res);
                  let currs = dataSource.filter((d) => d.id === res.id);
                  if (currs.length) {
                    currs[0].value = JSON.stringify(res.value);
                    console.log(dataSource);
                    setDataSource(dataSource);
                    actionRef.current?.reload();
                    setOpen(false);
                  }
                }
              }}
              type="primary"
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form2}>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item label="内容项" name="name">
            {form2.getFieldValue("name")}
          </Form.Item>
          <Form.Item label="详细说明" name={["value", "content"]}>
            <Input />
          </Form.Item>
          <Form.Item label="排序值" name={["value", "sort"]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
